﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using eBay.Service.Core.Sdk;
using eBay.Service.Core.Soap;
using eBay.Service.Util;

namespace SaleDiscount.Portal.eBay
{
    /// <summary>
    /// Summary description for ApiContextLoader.
    /// </summary>
    public class ApiContextLoader
    {

        private static Mutex mRetry = new Mutex();
        private static CallRetry retry;
        private ApiContext ctx;
        public ApiContextLoader()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        //private static ApiContext GetContext(string appid, string devid, string cert, string token)
        //{
        //    if (ctx != null)
        //        return ctx;

        //    try
        //    {
        //        mCtx.WaitOne();
        //        if (ctx != null)
        //            return ctx;

        //        ctx = LoadApiContext(appid, devid, cert, token);
        //        ctx.CallRetry 
        //        return ctx;
        //    }
        //    finally
        //    {
        //        mCtx.ReleaseMutex();
        //    }
        //}


        private static CallRetry GetCallRetry()
        {
            if (retry != null)
                return retry;

            try
            {
                mRetry.WaitOne();
                if (retry != null)
                    return retry;

                retry = new CallRetry();
                retry.DelayTime = Convert.ToInt32(LoadAppConfig("DelayTime"));
                retry.MaximumRetries = Convert.ToInt32(LoadAppConfig("MaximumRetries"));
                // retry.TriggerErrorCodes
                // retry.TriggerExceptions
                return retry;
            }
            finally
            {
                mRetry.ReleaseMutex();
            }
        }
        public static ApiContext LoadApiContext( string token, string ebayUser)
        {
            ApiContext context = new ApiContext();

            context.ApiCredential.ApiAccount.Application = LoadAppConfig("Environment.AppId");
            context.ApiCredential.ApiAccount.Developer = LoadAppConfig("Environment.DevId");
            context.ApiCredential.ApiAccount.Certificate = LoadAppConfig("Environment.CertId");
            context.ApiCredential.eBayToken = token;// LoadAppConfig(token);
            context.SoapApiServerUrl = LoadAppConfig("Environment.ApiServerUrl");
            context.SignInUrl = LoadAppConfig("Environment.SignInUrl");
            context.RuName = LoadAppConfig("RunName");

            context.ApiCredential.eBayAccount = new eBayAccount();
            context.ApiCredential.eBayAccount.UserName = ebayUser;
            context.EPSServerUrl = LoadAppConfig("Environment.EpsServerUrl");
            context.Version = LoadAppConfig("Version");
            context.Timeout = Convert.ToInt32(LoadAppConfig("TimeOut"));
            context.Site = SiteCodeType.US;

            ApiLogManager Logger = new ApiLogManager();
            Logger.EnableLogging = Convert.ToBoolean(LoadAppConfig("LoggingEnabled"));
            if (Logger.EnableLogging)
            {
                string logfile = LoadAppConfig("logfile");
                if (!string.IsNullOrEmpty(logfile))
                {
                    if (HttpContext.Current != null)//in web
                        Logger.ApiLoggerList.Add(new FileLogger(Path.Combine(HttpContext.Current.Server.MapPath("~/"), logfile)));
                    else
                    {
                        Logger.ApiLoggerList.Add(new FileLogger(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, logfile)));
                    }


                    if (LoadAppConfig("logexception").ToUpper() == "TRUE")
                        Logger.ApiLoggerList[0].LogExceptions = true;

                    if (LoadAppConfig("logmessages").ToUpper() == "TRUE")
                        Logger.ApiLoggerList[0].LogApiMessages = true;
                    Logger.ApiLoggerList[0].LogInformations = true;

                }



            }
            context.ApiLogManager = Logger;
            context.CallRetry = GetCallRetry();
            return context;
        }

        public static string LoadAppConfig(string key)
        {
            return ConfigurationSettings.AppSettings.Get(key);
        }
        public static string LaunchSignInPage(ApiContext context, string sessionID)
        {
            if (context == null)
                throw new SdkException("Please specify the Context.", new System.ArgumentNullException());

            if (string.IsNullOrWhiteSpace(context.SignInUrl))
                throw new SdkException("Please specify the SignInUrl in the Context object.", new System.ArgumentNullException());

            if (string.IsNullOrEmpty(context.RuName))
                throw new SdkException("Please specify a RuName.", new System.ArgumentNullException());

            // Go to the page.
            string finalUrl = context.SignInUrl + "&runame=" + context.RuName;
            if (!string.IsNullOrEmpty(sessionID))
                finalUrl += "&sessid=" + sessionID;

            return finalUrl;
        }

    }
}

